package com.pactera.madp.cp.service.impl;

import com.pactera.madp.cp.api.feign.RemoteDeptService;
import org.apache.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.cp.api.dto.daily.DailySendDTO;
import com.pactera.madp.cp.api.entity.WorkEmployeeEntity;
import com.pactera.madp.cp.api.entity.daily.WorkDailySendEntity;
import com.pactera.madp.cp.api.vo.daily.DailySendVo;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.WorkDailySendMapper;
import com.pactera.madp.cp.service.IWorkDailySendService;
import com.pactera.madp.cp.service.IWorkEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WorkDailySendServiceImpl extends ServiceImpl<WorkDailySendMapper, WorkDailySendEntity> implements IWorkDailySendService {

    @Autowired
    private IWorkEmployeeService workEmployeeService;
    @Autowired
    private RemoteDeptService remoteService;

    @Override
    public boolean updateSend(DailySendDTO dto) {
        Integer corpId = CorpContextHolder.getCorpId();
        WorkDailySendEntity sendEntity = copy(dto, corpId);
        UpdateWrapper<WorkDailySendEntity> wrapper = new UpdateWrapper<WorkDailySendEntity>();
        wrapper.lambda().eq(WorkDailySendEntity::getCorpId, corpId);
        return this.saveOrUpdate(sendEntity, wrapper);
    }

    @Override
    public DailySendVo querySend() {
        DailySendVo vo = new DailySendVo();

        Integer corpId = CorpContextHolder.getCorpId();
        this.lambdaQuery().eq(WorkDailySendEntity::getCorpId, corpId).list();
        List<WorkDailySendEntity> entities = this.lambdaQuery().eq(WorkDailySendEntity::getCorpId, corpId).list();
        WorkDailySendEntity workDailySendEntity;
        if (entities.size() < 1) {
            workDailySendEntity = new WorkDailySendEntity();
            workDailySendEntity.setCorpId(corpId);
            workDailySendEntity.setOrder(false);
            this.save(workDailySendEntity);
        } else {
            workDailySendEntity = entities.get(0);
        }
//        List<WorkEmployeeEntity> employees = employees(workDailySendEntity.getEmployeeIds());
        List<Map<String, Object>> depts = depts(workDailySendEntity.getDeptIds());
        List<Map<String, Object>> users = users(workDailySendEntity.getUserIds());

        List<String> contactList = getContactList(workDailySendEntity);
        List<String> roomList = getRoomList(workDailySendEntity);
        List<String> typeList = getTypeList(workDailySendEntity);
        vo.setContacts(contactList);
        vo.setRooms(roomList);
        vo.setDailyType(typeList);
//        vo.setEmployees(employees);
        vo.setDepts(depts);
        vo.setUsers(users);
        vo.setIsOrder(workDailySendEntity.isOrder());
        return vo;
    }

    private List<WorkEmployeeEntity> employees(String employeeIds) {
        List<WorkEmployeeEntity> list = new ArrayList<>();
        if (StringUtils.isNotBlank(employeeIds)) {
            List<String> asList = Arrays.asList(employeeIds.split(","));
            QueryWrapper<WorkEmployeeEntity> wrapper = new QueryWrapper<WorkEmployeeEntity>();
            wrapper.in("id", asList);
            list = workEmployeeService.list(wrapper);
        }
        return list;
    }

    private List<Map<String, Object>> depts(String deptIds) {
        List<Map<String, Object>> list = new ArrayList<>();
        if (StringUtils.isNotBlank(deptIds)) {
            List<Integer> asList = Arrays.asList(deptIds.split(",")).stream().map(Integer::valueOf).collect(Collectors.toList());
            list = remoteService.depts(asList);
        }
        return list;
    }

    private List<Map<String, Object>> users(String userIds) {
        List<Map<String, Object>> list = new ArrayList<>();
        if (StringUtils.isNotBlank(userIds)) {
            List<Integer> asList = Arrays.asList(userIds.split(",")).stream().map(Integer::valueOf).collect(Collectors.toList());
            list = remoteService.users(asList);
        }
        return list;
    }

    @Override
    public String getSendEmployee(Integer corpId) {
        String employeeIds = this.lambdaQuery().select(WorkDailySendEntity::getEmployeeIds).eq(WorkDailySendEntity::getCorpId, corpId).list().get(0).getEmployeeIds();
        String[] split = employeeIds.split(",");
        List<String> collect = workEmployeeService.lambdaQuery().in(WorkEmployeeEntity::getId, split).select(WorkEmployeeEntity::getWxUserId).list().stream().map(m -> m.getWxUserId()).collect(Collectors.toList());
        String join = org.apache.commons.lang.StringUtils.join(collect, '|');
        return join;
    }
    WorkDailySendEntity copy(DailySendDTO dto, Integer corpId) {
//        String ids = "";
//        List<String> wxIds = dto.getWxIds();
//        QueryWrapper<WorkEmployeeEntity> wrapper = new QueryWrapper<>();
//        wrapper.select("id").eq("corp_id", corpId)/*.in("wx_user_id", wxIds)*/;
//        List<Object> objects = workEmployeeService.getBaseMapper().selectObjs(wrapper);
//        for (Object id : objects) {
//            if (!id.equals("")) {
//                ids =  ids + id.toString() + ',';
//            }
//        }
//        if (ids.length() > 0) {
//            ids = ids.substring(0, ids.length()-1);
//        }

        WorkDailySendEntity workDailySendEntity = new WorkDailySendEntity();
//        workDailySendEntity.setEmployeeIds(ids);
        List<String> contacts = dto.getContacts();
        List<String> rooms = dto.getRooms();
        List<String> dailyTypes = dto.getDailyType();
        List<String> names = getNames(workDailySendEntity.getClass().getDeclaredFields());
        names.forEach(name -> {
            if (contacts.contains(name)) {
                setFieldValueByName(workDailySendEntity, name, true);
            }
            if (rooms.contains(name)) {
                setFieldValueByName(workDailySendEntity, name, true);
            }
            if (dailyTypes.contains(name)) {
                setFieldValueByName(workDailySendEntity, name, true);
            }
        });
        List<Integer> userIdList = dto.getUserIds();
        List<Integer> deptIdList = dto.getDeptIds();
        String userIds = userIdList == null ? "" : userIdList.stream().map(String::valueOf).collect(Collectors.joining(","));
        workDailySendEntity.setUserIds(userIds);
        String deptIds = deptIdList == null ? "" : deptIdList.stream().map(String::valueOf).collect(Collectors.joining(","));
        workDailySendEntity.setDeptIds(deptIds);
        workDailySendEntity.setOrder(dto.getIsOrder());
        return workDailySendEntity;
    }
    //获取对象所有属性
    List<String> getNames(Field[] fields) {
        List<String> names = new ArrayList<>();
        for (Field field : fields) {
            names.add(field.getName());
        }
        return names;
    }
    //根据属性名更改属性
    void setFieldValueByName(Object obj, String fieldName, Object value) {

        try {
            Field f = obj.getClass().getDeclaredField(fieldName);
            f.setAccessible(true);
            f.set(obj, value);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    List<String> getContactList(WorkDailySendEntity entity) {
        ArrayList<String> list = new ArrayList<>();
        if (entity.isContactTotalContact()) list.add("contactTotalContact");
        if (entity.isContactLossContact()) list.add("contactLossContact");
        if (entity.isContactRealAddContact()) list.add("contactRealAddContact");
        if (entity.isContactChangeContact()) list.add("contactChangeContact");
        return list;

    }
    List<String> getTypeList(WorkDailySendEntity entity) {
        ArrayList<String> list = new ArrayList<>();
        if (entity.isDaily()) list.add("daily");
        if (entity.isWeekly()) list.add("weekly");
        if (entity.isMonthly()) list.add("monthly");
        return list;
    }
    List<String> getRoomList(WorkDailySendEntity entity) {
        ArrayList<String> list = new ArrayList<>();
        if (entity.isTotalRoom()) list.add("totalRoom");
        if (entity.isChangeRoom()) list.add("changeRoom");
        if (entity.isChangeContact()) list.add("changeContact");
        if (entity.isTotalContact()) list.add("totalContact");
        if (entity.isRealAddContact()) list.add("RealAddContact");
        if (entity.isLossContact()) list.add("lossContact");
        return list;
    }
}
